package audio;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

import utils.StackTracePrinter;


public class SoundEventSound extends SpotSound {

	private static final float TRANSITION_DURATION = 1.0f;
	String[] attributes;
	byte[] byteArray;

	public SoundEventSound(String filePath, String[] attributes) throws IOException, UnsupportedAudioFileException, LineUnavailableException {
		this.attributes = attributes;
		soundFile = new File(filePath);
		prepareAudioStream();
	}

	

	
	
	@Override
	public void stopSound() {
		clip.stop();
		clip.close();
	}


	@Override
	public void playSound() {
		new Thread (new Runnable() {
			
			@Override
			public void run() {
				float bytesPerSecond = format.getFrameSize()*format.getFrameRate();
				try {
					audioInputStream.skip((long)(bytesPerSecond*new Float(attributes[3])));
					byteArray = new byte[(int)(bytesPerSecond*new Float(attributes[4]))];
					audioInputStream.read(byteArray, 0, byteArray.length);

				} catch (IOException e) {
					StackTracePrinter.print(e);
					return;
				}

				if (attributes[0].equals("true") || attributes[1].equals("true")) {
					/**
					 * The function reads two sample sequences from <code>active</code> and
					 * <code>next</code> and writes the result into <code>result</code>
					 *
					 * @param active     Currently active stream.
					 * @param next       Stream to switch/transition to.
					 * @param srcOffset  Position of the first byte to read.
					 * @param result     Array to write the transition to.
					 * @param dstOffset  Position of the first byte to write.
					 * @param frameCount Transition length in sample frames.
					 * @param format     Stream description.
					 */
					OutInFader.process(new Boolean(attributes[1]), new Boolean(attributes[2]), byteArray, 0,
							byteArray, 0, (int)(format.getFrameRate()*TRANSITION_DURATION), format);
				}
				try {
					clip.open(format, byteArray, 0, byteArray.length);
				} catch (LineUnavailableException e) {
					StackTracePrinter.print(e);
					return;
				}
				clip.start();
			}
		}).start();
		
	}


}